<script setup lang="ts">
import VDialog from "@/components/VDialog/VDialog.vue";
import { computed, reactive, ref, watch } from "vue";
import {
  AddTeachingWorkloadCommand,
  TeachingWorkloadPageResponse,
  UpdateTeachingWorkloadCommand,
  addTeachingWorkloadApi,
  updateTeachingWorkloadApi
} from "@/api/performance/teaching";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { getAllUsersSimpleApi, type UserSimpleDTO } from "@/api/system/user";

interface Props {
  type: "add" | "update";
  modelValue: boolean;
  row?: TeachingWorkloadPageResponse;
}

const props = defineProps<Props>();
const emits = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set(v) {
    emits("update:modelValue", v);
  }
});

const formData = reactive<AddTeachingWorkloadCommand | UpdateTeachingWorkloadCommand>({
  id: undefined,
  userId: undefined,
  assessmentYear: new Date().getFullYear(),
  generalCourseScore: 0,
  subjectCourseScore: 0,
  labCourseScore: 0,
  totalTeachingScore: 0
});

// 用户搜索相关
const allUsers = ref<UserSimpleDTO[]>([]);
const userOptions = ref<UserSimpleDTO[]>([]);

async function fetchAllUsersSimple() {
  try {
    const { data } = await getAllUsersSimpleApi();
    allUsers.value = data || [];
    userOptions.value = allUsers.value;
  } catch (e) {
    console.error(e);
  }
}

function remoteSearchUsers(query: string) {
  const q = (query || "").trim();
  if (!q) {
    userOptions.value = allUsers.value;
    return;
  }
  const lower = q.toLowerCase();
  userOptions.value = allUsers.value.filter(u =>
    (u.nickname || "").toLowerCase().includes(lower) ||
    (u.deptName || "").toLowerCase().includes(lower)
  );
}

function getUserLabel(u: UserSimpleDTO) {
  const name = u.nickname || "";
  const dept = u.deptName || "";
  return dept ? `${name}（${dept}）` : name;
}

// 自动计算总教学分数
const totalTeachingScore = computed({
  get: () => {
    const general = Number(formData.generalCourseScore || 0);
    const subject = Number(formData.subjectCourseScore || 0);
    const lab = Number(formData.labCourseScore || 0);
    return general + subject + lab;
  },
  set: (val) => {
    // 只读，不允许手动设置
    formData.totalTeachingScore = val;
  }
});

// 监听分数字段变化，自动更新总分数
watch(
  [() => formData.generalCourseScore, () => formData.subjectCourseScore, () => formData.labCourseScore],
  () => {
    formData.totalTeachingScore = totalTeachingScore.value;
  },
  { immediate: true }
);

const rules: FormRules = {
  userId: [
    {
      required: true,
      message: "请选择用户"
    }
  ],
  assessmentYear: [
    {
      required: true,
      message: "考核年度不能为空"
    }
  ]
};

const formRef = ref<FormInstance>();
async function handleOpened() {
  // 加载用户列表
  await fetchAllUsersSimple();
  
  if (props.row) {
    Object.assign(formData, props.row);
  } else {
    formRef.value?.resetFields();
  }
}

const loading = ref(false);
async function handleConfirm() {
  try {
    loading.value = true;
    if (props.type === "add") {
      await addTeachingWorkloadApi(formData);
    } else if (props.type === "update") {
      await updateTeachingWorkloadApi(formData as UpdateTeachingWorkloadCommand);
    }
    ElMessage.info("提交成功");
    visible.value = false;
    emits("success");
  } catch (e) {
    console.error(e);
    ElMessage.error((e as Error)?.message || "提交失败");
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <v-dialog
    show-full-screen
    :fixed-body-height="false"
    use-body-scrolling
    :title="type === 'add' ? '新增教学工作量' : '更新教学工作量'"
    v-model="visible"
    :loading="loading"
    @confirm="handleConfirm"
    @cancel="visible = false"
    @opened="handleOpened"
  >
    <el-form :model="formData" label-width="140px" :rules="rules" ref="formRef">
      <el-form-item prop="userId" label="用户" required>
        <el-select
          v-model="formData.userId"
          filterable
          remote
          reserve-keyword
          placeholder="搜索并选择用户"
          :remote-method="remoteSearchUsers"
          style="width: 50%"
          clearable
        >
          <el-option
            v-for="u in userOptions"
            :key="u.userId"
            :label="getUserLabel(u)"
            :value="u.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item prop="assessmentYear" label="考核年度" required>
        <el-input-number 
          :min="2000" 
          :max="2100" 
          v-model="formData.assessmentYear" 
          style="width: 50%"
          placeholder="请输入考核年度"
        />
      </el-form-item>

      <el-form-item prop="generalCourseScore" label="通用课程分数">
        <el-input-number 
          :min="0" 
          v-model="formData.generalCourseScore" 
          style="width: 50%"
          :precision="2"
          placeholder="请输入分数"
        />
      </el-form-item>

      <el-form-item prop="subjectCourseScore" label="专业课程分数">
        <el-input-number 
          :min="0" 
          v-model="formData.subjectCourseScore" 
          style="width: 50%"
          :precision="2"
          placeholder="请输入分数"
        />
      </el-form-item>

      <el-form-item prop="labCourseScore" label="实验课程分数">
        <el-input-number 
          :min="0" 
          v-model="formData.labCourseScore" 
          style="width: 50%"
          :precision="2"
          placeholder="请输入分数"
        />
      </el-form-item>

      <el-form-item prop="totalTeachingScore" label="总教学分数">
        <el-input-number 
          :min="0" 
          :model-value="totalTeachingScore"
          style="width: 50%"
          :precision="2"
          disabled
          placeholder="自动计算"
        />
      </el-form-item>
    </el-form>
  </v-dialog>
</template>

<style scoped>
:deep(.el-form-item__content) {
  display: flex;
  justify-content: center;
}
</style>
